﻿using Md.Api.Entity.DapperModels.MdDB;
using Md.Api.Model.Manage.SysMenu.Request;
using Md.Dapper.Repositories.Md;

namespace Md.Api.Service.Manage.SysMenu;
/// <summary>
/// 通过用户获取系统菜单树列表服务
/// </summary>
public class GetSysMenuTreeListByUserService : ApiBase<RequestGetSysMenuTreeListByUserModel>
{
    /// <summary>
    /// 系统菜单仓储
    /// </summary>
    public SysMenuRep sysMenuRep { get; set; }
    /// <summary>
    /// 执行
    /// </summary>
    protected override void ExecuteMethod()
    {
        var menus = sysMenuRep.GetSysMenuListByUserId(Parameter.UserId).ToList();

        var res = BuildMenuTree(menus, 0);

        Result.Data = res;
    }

    public List<SysMenuModel> BuildMenuTree(List<SysMenuModel> menus, long parentId)
    {
        var result = new List<SysMenuModel>();

        var list = menus.Where(s => s.ParentId == parentId).ToList();

        foreach (var menu in list)
        {
            result.Add(menu);

            var children = BuildMenuTree(menus, menu.MenuId);

            if (children.Count() > 0)
            {
                menu.Children = children;
            }
        }

        return result;
    }
}